package com.zoe.onelink.logging.trace.feign.client;

import brave.Span;
import brave.Tracer;
import com.zoe.onelink.common.constant.TraceSpanConstant;
import com.zoe.onelink.util.OnelinkContextHolder;
import com.zoe.onelink.util.SpringUtil;
import feign.Client;
import feign.Request;
import feign.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-09-14
 */
@Slf4j
@RequiredArgsConstructor
public class OnelinkFeignTraceClient implements Client {

    private final Client client;

    private Tracer tracer;

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        this.traceFeignRequest(request);
        return client.execute(request, options);
    }

    private void traceFeignRequest(Request request) {
        if (this.tracer == null) {
            this.tracer = SpringUtil.getBean(Tracer.class);
        }
        try {
            String url = request.url();
            if (log.isDebugEnabled()) {
                log.info("Feign actual call [{}] [{}] [{}]", request.requestTemplate().feignTarget().name(), request.httpMethod(), url);
            }
            Span span = this.tracer.currentSpan();
            span.tag(TraceSpanConstant.RPC_REMOTE_ADDR, url);
            OnelinkContextHolder.putValue(TraceSpanConstant.RPC_REMOTE_ADDR, url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
